<?php
/**
 * 商品
 * @author 江羿平<hugcolin@163.com>
 */

use Core\AdminController;
use Models\Product;
use Models\Item;
use Models\Brand;
use Models\Category;
use Models\Supplier;
use Models\Spec;
use Models\PurchaseRecord;

class ProductController extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->lang->load('admin_product', $this->session->admin_language);
    }

    public function search()
    {
        $product = new Product;
        $keyword = $this->input->get('keyword');
        $product->like('title', trim($keyword));
        $product->or_like('en_title', trim($keyword));
        $data['products'] = $product->select('id,title,en_title')->order_by('sort', 'desc')->paginate(10);

        return $this->response($data['products']->to_array());
    }

    /**
     * 列表页
     */
    public function index()
    {
        $product = new Product;
        $category_id = $this->input->get('category_id');
        $category_id2 = $this->input->get('category_id2');
        $brand_id = $this->input->get('brand_id');
        $status = $this->input->get('status');
        $is_hot = $this->input->get('is_hot');
        $keyword = $this->input->get('keyword');

        if (trim($keyword)) {
            $item = (new Item)->where('barcode', $keyword)->get_one();
            if ($item) {
                $product->where('id', $item['product_id']);
            } else {
                $product->group_start();
                $product->like('title', trim($keyword));
                $product->or_like('en_title', trim($keyword));
                $product->group_end();
            }
        }

        if ($category_id) {
            $product->where('category_id', $category_id);
        }
        if ($category_id2) {
            $product->where('category_id2', $category_id2);
        }
        if ($brand_id) {
            $product->where('brand_id', $brand_id);
        }
        if ($status === '0' || $status == 1) {
            $product->where('status', $status);
        }
        if ($status == 2) {
            //库存预警
            $product->where('id in (select product_id from items where stock <= danger_stock)');
        }
        if ($status == 3) {
            $product->where('id in (select product_id from purchase_records where stock >0 and expire<'.time().')');
        }

        if ($is_hot === '0' || $is_hot == 1) {
            $product->where('is_hot', $is_hot);
        }

        $data['products'] = $product->order_by('sort', 'desc')->paginate(20);

        if ($this->input->is_ajax_request()) {
            return $this->response($data['products']->to_array());
        }

        $brand = new Brand;
        $data['brands'] = $brand->order_by('en_title', 'asc')->get();
        $data['brands'] = arr_key($data['brands']);
        $category = new Category;
        $data['categorys'] = $category->where("parent_id", 0)->order_by('sort', 'desc')->get();

        $cate_id = array();
        $product_ids = [];
        foreach ($data['products'] as $p) {
            $cate_id[] = $p['category_id'];
            $cate_id[] = $p['category_id2'];
            if ($p['status']) {
                $product_ids[] = $p['id'];
            }
        }

        $data['sub_categories'] = $category_id ? Category::where('parent_id', $category_id)->get() : [];
        $data['product_cates'] = array();
        if (!empty($cate_id)) {
            $data['product_cates'] = $category->where_in('id', $cate_id)->get();
            $data['product_cates'] = arr_key($data['product_cates']);
        }

        $dangers = [];
        $expires = [];
        if (!empty($product_ids)) {
            $danger_items = (new Item)->select('product_id')->where_in('product_id', $product_ids)->where('stock<=danger_stock')->get();
            foreach ($danger_items as $d) {
                $dangers[] = $d['product_id'];
            }

            $expire_records = (new PurchaseRecord)->select('product_id')->where_in('product_id', $product_ids)->where('stock>', 0)->where('expire<', time())->get();
            foreach ($expire_records as $e) {
                $expires[] = $e['product_id'];
            }
        }

        $data['dangers'] = $dangers;
        $data['expires'] = $expires;
        //$this->output->enable_profiler(TRUE);
        $this->load->view('admin/product/index', $data);
    }



    /**
     * 添加页面
     */
    public function create()
    {
        $brand = new Brand;
        $data['brands'] = $brand->order_by('en_title', 'asc')->get();
        $category = new Category;
        $data['categorys'] = $category->where("parent_id", 0)->order_by('sort', 'desc')->get();
        $data['categorys2'] = [];

        $data['back_url'] = $this->input->server('HTTP_REFERER');
        $this->load->helper('form');
        $data['supplier'] = (new Supplier)->get();
        $data['specs'] = (new Spec)->order_by('sort desc')->get();

        $this->load->view('admin/product/create', $data);
    }

    /**
     * 编辑页面
     */
    public function edit($id)
    {
        $product = new Product;
        $brand = new Brand;
        $data['brands'] = $brand->order_by('en_title', 'asc')->get();
        $category = new Category;
        $data['categorys'] = $category->where("parent_id", 0)->order_by('sort', 'desc')->get();
        $data['product'] = $product->find(intval($id));
        if ($data['product']['category_id']) {
            $data['categorys2'] = $category->where("parent_id", $data['product']['category_id'])->order_by('sort', 'desc')->get();
        }
        $item = new Item;
        $data['items'] = $item->where('product_id', $id)->where('is_delete', 0)->order_by('id', 'asc')->get();
        $data['back_url'] = $this->input->server('HTTP_REFERER');
        $this->load->helper('form');
        $data['supplier'] = (new Supplier)->get();
        $data['specs'] = (new Spec)->order_by('sort desc')->get();
        if ($product['recommends']) {
            $ids = explode(',', $product['recommends']);
            $data['recommends'] = Product::where_in('id', $ids)->get();
        }

        $this->load->view('admin/product/create', $data);
    }

    /**
     * 删除
     */
    public function delete()
    {
        $product = new Product;
        $product->update($this->input->post('id'), array('is_delete' => 1));
        $item = new Item;
        $item->where(array(
             'product_id' => $this->input->post('id')
         ))->updateAll(array(
             'is_delete' => 1
         ));

        echo json_encode(array('code' => 0,'msg' => 'ok'));
    }

    /**
     * 删除规格
     */
    public function delete_item()
    {
        $item = new Item;
        $item->update($this->input->post('id'), array('is_delete' => 1));
        echo json_encode(array('code' => 0,'msg' => 'ok'));
    }


    /**
     * 提交保存
     */
    public function save()
    {
        $unit_id = 0;
        if ($this->input->post('add_unit') && $this->input->post('add_unit_en')) {
            $spec = new Spec;
            $data = [
                'title' => $this->input->post('add_unit'),
                'en_title' => $this->input->post('add_unit_en'),
                'sort' => 0,
                'create_time' => time(),
            ];
            $unit_id = $spec->add($data);
        }
        $product = new Product;
        $product->load($this->input->post());
        $product['sort'] = intval($this->input->post('sort'));
        $product['is_hot'] = intval($this->input->post('is_hot'));
        $product['is_cashier_hot'] = intval($this->input->post('is_cashier_hot'));
        $product['is_weight'] = intval($this->input->post('is_weight'));
        $product['is_new'] = intval($this->input->post('is_new'));
        $product['is_recommend'] = intval($this->input->post('is_recommend'));
        $product['hits'] = intval($this->input->post('hits'));
        if ($this->input->post('images')) {
            $product['images'] = implode(',', $this->input->post('images'));
        }
        if ($this->input->post('recommends')) {
            $product['recommends'] = implode(',', $this->input->post('recommends'));
        }
        $product['update_time'] = time();
        if ($unit_id > 0) {
            $product['unit'] = $unit_id;
        }

        if (!$product['title'] || !$product['category_id'] || !$product['category_id2'] || !$product['content'] || !$product['thumbnail'] || !$product['images']) {
            echo json_encode(array('code' => 2,'msg' => json_encode($data)));
            exit;
        }
        $items = $this->input->post('item');
        if (!$items) {
            echo json_encode(array('code' => 2,'msg' => json_encode($data)));
            exit;
        }



        $product_id = 0;
        if (intval($this->input->post('id'))) {
            $product_id = intval($this->input->post('id'));
            $product->update();
        } else {
            $product['create_time'] = time();
            $product_id = $product->add();
            if (!$product_id) {
                echo json_encode(array('code' => 1));
            }
        }

        $product_item = new Item;
        $item_data['product_id'] = $product_id;
        foreach ($items['title'] as $i => $title) {
            $item_data['title'] = $title;
            $item_data['en_title'] = $items['en_title'][$i];
            $item_data['original_price'] = floatval($items['original_price'][$i]);
            $item_data['price'] = floatval($items['price'][$i]);
            if ($items['tax'][$i] > 0) {
                $item_data['tax'] = round($item_data['original_price'] * 1 / 6, 2);
            } else {
                $item_data['tax'] = 0;
            }
            //$item_data['tax'] = $items['tax'][$i]>0?round(,2):0;
            $item_data['barcode'] = $items['barcode'][$i];
            $item_data['weight'] = $items['weight'][$i];
            $item_data['danger_stock'] = intval($items['danger_stock'][$i]);

            if (!isset($items['id'][$i])) {
                $items['id'][$i] = $product_item->add($item_data);
            } else {
                $item_data['stock'] = $items['stock'][$i];
                $product_item->update($items['id'][$i], $item_data);
            }

            if (isset($items['stock'][$i]) && $items['stock'][$i] > $items['last_stock'][$i]) {
                // 修改库存增加进货记录
                $purchase_record = new PurchaseRecord();
                $purchase_record->load([
                    'product_id' => $product_id,
                    'item_id' => $items['id'][$i],
                    'number' => $items['stock'][$i] - $items['last_stock'][$i],
                    'price' => $items['price'][$i],
                    'create_time' => time(),
                    'expire' => isset($items['expire'][$i]) ? strtotime($items['expire'][$i]) : time() + 3600 * 24 * 200,
                    'stock' => $items['stock'][$i]
                ]);
                $purchase_record->add();
            }
        }

        $product->update($product_id, [
            'price' => $items['price'][0],
            'original_price' => $items['original_price'][0]
        ]);

        return $this->response([
            'code' => 0,
            'msg' => 'ok',
            'product_id' => $product_id,
        ]);
    }

    public function multi_shangjia()
    {
        $ids = $this->input->post('ids');
        $value = $this->input->post('value');

        Product::where_in('id', $ids)->updateAll([
            'status' => $value
        ]);

        return $this->response(['code' => 0,'msg' => 'ok']);
    }

    public function multi_fenlei()
    {
        $ids = $this->input->post('ids');
        $category_id1 = $this->input->post('category_id1');
        $category_id2 = $this->input->post('category_id2');

        Product::where_in('id', $ids)->updateAll([
            'category_id' => $category_id1,
            'category_id2' => $category_id2
        ]);

        return $this->response(['code' => 0,'msg' => 'ok']);
    }
}
